<!DOCTYPE html>
<html>
<head>
    <title>课程转换</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">

</head>
<body>
    {% include 'show_ins_info.html' %}
    <div id="inputContents">
        <h3>会员编码及姓名：</h3>
        
        <input type="text" id="cusNameInput" style="width: 120px;" oninput="handleInput()">
        <ul id="cusNameResultList"></ul>
        <p></p>

        <div id="validCardsBox">
            <h4>卡号</h4>
            <select id="cardSel">
                <option value="">--无有效卡号--</option>
            </select>
        </div>
        <div id="cardInfo"></div>

        <hr>
        <div id="targetCls">转换成：DMS放松拉伸课程</div>

        
    </div>
    <p></p>
    <div id="showDealResult"></div>
    <div><button id='submitBtn' style="margin-right:5px;" onclick="submit()" disabled>提交</button></div>

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script> 
        let insId;
        let cus_list;
        let selectedName;
        let tmplt_info;
        let validData;
        let insRole;
        let insName;
    
        

        // 使用DOMContentLoaded事件监听，在页面加载完成后触发获取数据的操作
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();
            


            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;
                console.log('template info:',data)
                  })
                .catch(error => console.error('Error:', error));


            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                //将data赋值给块变量cus_list，供后面的handleInput使用
                    cus_list=data
                })
            .catch(error => console.error('Error:', error));
            // 这里可以通过 JavaScript 来遍历某个文件夹中的文件，生成名字列表
            // var names = ["Alice", "Bob", "Charlie", "David"];    
            
            const insInfos=hideInsSelectBlockAndGetInsInfo();
            insId=insInfos['sessionInsId'];
            insName=insInfos['sessionInsName'];
            insRole=insInfos['sessionInsRole'];

            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            
            
        });
        
  

        function getValidCards(){         
            const today=dateToString(new Date(),'date');
            const cardSel=document.getElementById('cardSel');
            cardSel.innerHTML=`<option value=''>--无有效卡号--</option>`;
            const cardInfo=document.getElementById('cardInfo');
            cardInfo.innerHTML='';
            const submitBtn=document.getElementById('submitBtn');

            fetch('/get_valid_cards_list',{
            method:"POST",
            headers:{
                "Content-Type":"application/json"
            },
            body: JSON.stringify({'cus_id':document.getElementById('cusNameInput').value.trim(),'today':today})
            })
            .then(response=>response.json())
            .then(data=>{
                console.log('valid data:',data)
                if(data['res']==='ok'){
                    validData=data['data']
                    showValidCard(validData);
                    submitBtn.disabled=false;
                }else{
                    cardSel.innerHTML=`<option value=''>--无有效卡号--</option>`;
                    submitBtn.disabled=true;
                }
                
            })
            .catch(error=>{
                console.log(error)
            });
        }

        function showValidCard(data){
            // console.log(data);
            const cardSel=document.getElementById('cardSel');      
            cardSel.innerHTML='';  
            const cardInfo=document.getElementById('cardInfo');
            cardInfo.innerHTML='';

            //满足限时课程，15节/30天则加入列表
            for(const order in data){
                if(data[order]['buy_type']==='限时课程' && data[order]['buy_num']===15 && data[order]['buy_cls_days']===30){
                    const opt=document.createElement('option');
                    opt.text=data[order]['card_id'];
                    opt.value=data[order]['card_id'];
                    cardSel.appendChild(opt);
                }

            }

            cardSel.addEventListener('change',showCardInfo());

            const eve=new Event('change');
            cardSel.dispatchEvent(eve);
            
        }

        function showCardInfo(){
            const cardInfo=document.getElementById('cardInfo');
            cardInfo.innerHTML='';
            const cardId=document.getElementById('cardSel').value;
            for(const order in validData){
                if(cardId===validData[order]['card_id']){
                    cardInfo.innerHTML=`<div style='padding:10px;'><div style='font-size:13px;color:#cfa227;'>· ${validData[order]['buy_type']}/${validData[order]['buy_cls_name']}  
                    &nbsp;&nbsp;${parseInt(validData[order]['cls_qty'])}节 / ${validData[order]['buy_cls_days']}天</div>
                    <div style='font-size:13px;color:#b134eb;margin-top:10px;font-weight:bold;'>· 该卡已转换节数 <span style='color:red;'>${parseInt(validData[order]['transfered_num'])}</span> 节</div>
                    <div style='font-size:13px;color:#cfa227;margin-top:10px;'>· 剩余可转换节数 <span style='color:red;'>${parseInt(validData[order]['cls_qty'])-parseInt(validData[order]['cls_tkn_qty'])}</span> 节</div></div>`;
                    

                    const transNum=document.createElement('input');
                    transNum.id='transNumInput';
                    transNum.width='10px';
                    transNum.type='number';
                    transNum.max=Math.max(0,parseInt(validData[order]['cls_qty'])-parseInt(validData[order]['cls_tkn_qty']));
                    transNum.min=0;
                    transNum.value=3;
                    const transDiv=document.createElement('div');
                    transDiv.innerHTML=`<span style='font-size:14px;font-weight:bold;color:#2775cf;'>请输入要转换的节数: </span>`;
                    transDiv.appendChild(transNum);


                    transNum.addEventListener('input', function() {
                        const max = this.max;
                        if (parseInt(this.value) > max) {
                            // alert(`请确保值不超过 ${max}`);
                            this.value = max; // 选项：将输入值重置为 max
                        }
                    }); 

                    cardInfo.appendChild(transDiv);

                    break;
                }
            }

        }

     

        function submit(){
            let insIdPage;
            if(insRole==='ins'){
                insIdPage=insId;
            }else{
                //特殊，陆的情况
                if(insRole==='admin'){
                    if(insId==='LZADM002' || insId==='LZADM001'){
                        insIdPage='LZINS001';
                    }
                    
                }
            }
            const showDealResult=document.getElementById('showDealResult');
            showDealResult.innerHTML='正在转换。。。'
            const cardId=document.getElementById('cardSel').value;
            const transNum=document.getElementById('transNumInput').value;
            const today=new Date();

            const newDmsId=`LZD${dateToString(today,'digit14')}`;
            const newDmsBuyFlowId=`LZD${dateToString(today,'digit14')}-${dateToString(today,'digit14')}`;

            let data_origin={},data_dms_buy={},data_dms_card={},data={}

            // console.log('validData:',validData);
            for (const n in validData){
                
                if(validData[n]['card_id']===cardId){
                    data_origin={
                        'card_id':cardId,
                        'card_type':validData[n]['buy_type'],
                        'card_name':validData[n]['buy_cls_name'],
                        'cls_qty':parseInt(validData[n]['cls_qty'])-parseInt(transNum),
                        'card_start_time':validData[n]['start_time'],
                        'prd':validData[n]['buy_cls_days'],
                        'valid_time':validData[n]['valid_time'],
                        'end_time':validData[n]['end_time'],
                        'cmt':`部分已转换成DMS课程,DMS卡号：${newDmsId}`,
                        'opr_id':insId,
                        'opr_time':dateToString(today,'dateTime')
                        
                    };
                    data_dms_buy={
                        'cus_id':validData[n]['cus_id'],
                        'cus_name':validData[n]['cus_name'],
                        'buy_date':dateToString(today,'date'),
                        'card_id':newDmsId,
                        'buy_flow_id':newDmsBuyFlowId,
                        'buy_type':'常规课程',
                        'buy_cls_name':'DMS放松拉伸',
                        'buy_num':transNum,
                        'buy_cls_days':999,
                        'valid_time':'all_day',
                        'pay':0,
                        'real_pay':0,
                        'cashier_id':validData[n]['cashier_id'],
                        'income_type':'续课',
                        'comment':`从原有限时课程转换,原卡号：${cardId}`,
                        'operator_id':insId,
                        'operate_time':dateToString(today,'dateTime')
                    };

                    data_dms_card={
                        'card_id':newDmsId,
                        'card_type':'常规课程',
                        'card_name':'DMS放松拉伸',
                        'cls_qty':transNum,
                        'card_start_time':dateToString(today,'date'),
                        'prd':999,
                        'valid_time':'all_day',
                        'end_time':dateToString(today.setDate(today.getDate()+999),'date'),
                        'cmt':`从原有限时课程转换,原卡号：${cardId}`,
                        'opr_id':insId,
                        'opr_time':dateToString(today,'dateTime')
                        
                    };

                

                    if(Object.keys(data_origin).length>0 && Object.keys(data_dms_buy).length>0 && Object.keys(data_dms_card).length>0){
                        data={
                            'origin_card':data_origin,
                            'new_dms_buy':data_dms_buy,
                            'dms_card':data_dms_card
                        }
                    }

                    break;
                }
            }            

            // console.log('all transfer data:',data);

            try{
                fetch('/deal_transfer_lmt_to_dms', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body:JSON.stringify(data)
                    })
                .then(response => response.json())
                .then(data => {
                    console.log('deal transfer lmt to dms:',data)
                    if(data['res']==='ok'){
                        console.log(data['data']);
                        showDealResult.innerHTML='转换成功。'
                        alert('转换成功');
                        window.location.href='./index';
                    }else{
                        console.log('transfer failed:',data['error'])
                    }


                })
                .catch(error => console.error('Error:', error));
                 
            }catch(error){
                alert(error.message);
            }

        }



        function handleInput() {
            // 获取输入框中的值
            const submitBtn=document.getElementById('submitBtn');
            submitBtn.disabled=true;
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameResultList");
   

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";
            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = name;
                    

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        selectedName=name;      
                        document.getElementById("cusNameInput").value=name;                  
                       
                        resultList.innerHTML = "";  
                        resultList.style.display='none';

                        getValidCards();
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });
        
            resultList.classList.add("cus-list-result-blue");
            resultList.style.paddingLeft='20px';
        }
    
      

  
  


    </script>
</body>
</html>
